import React, { ReactElement, useContext, useEffect, useMemo } from 'react';
import { View } from 'react-native';

import styles from './style';
import { RoundType, UserRole } from '../../constant';
import { setAudioAvailable } from '../../../../util/RTC/rtcEngine';
import { getUserInfo } from '../../../../store/user';
import { Store } from '../../reducer';
import Talking from '../Talking';
import { setIsOpenMicrophone } from '../../actions';

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { showPrepare, currentPPT, currentTalkingUsers } = state;

  let isRestVideo = false;
  if (currentPPT.round) {
    const { roundInfoVideo, roundType } = currentPPT.round;
    isRestVideo =
      roundType === RoundType.Video && roundInfoVideo && roundInfoVideo.isRest;
  }

  const needOpenMicrophone = showPrepare || isRestVideo;

  const { role } = getUserInfo();
  const isStudent = role === UserRole.Student;

  useEffect((): void => {
    if (isStudent) {
      setIsOpenMicrophone(needOpenMicrophone);
      setAudioAvailable(needOpenMicrophone, 'classRoomRoundAboutMicrophone');
    }
  }, [isStudent, needOpenMicrophone]);

  return useMemo((): ReactElement => {
    if (needOpenMicrophone) {
      return (
        <View style={styles.container}>
          {currentTalkingUsers.map(
            (user): ReactElement => (
              <Talking headUrl={user.headUrl} name={user.userNickName} />
            )
          )}
        </View>
      );
    }

    return <View />;
  }, [currentTalkingUsers, needOpenMicrophone]);
};
